// messageStore.js - 消息存储服务

// 存储键名
const CHAT_MESSAGES_KEY = 'chat_messages_v3';
const CHAT_USER_DATA_KEY = 'chat_user_data_v3';

// 获取所有聊天消息
export const getAllMessages = () => {
  const saved = localStorage.getItem(CHAT_MESSAGES_KEY);
  return saved ? JSON.parse(saved) : [];
};

// 获取用户数据
export const getUserData = () => {
  const saved = localStorage.getItem(CHAT_USER_DATA_KEY);
  return saved ? JSON.parse(saved) : null;
};

// 保存新消息
export const saveMessage = (message) => {
  const messages = getAllMessages();
  const updatedMessages = [...messages, message];
  localStorage.setItem(CHAT_MESSAGES_KEY, JSON.stringify(updatedMessages));
  return updatedMessages;
};

// 获取最新消息
export const getLatestMessage = () => {
  const messages = getAllMessages();
  return messages.length > 0 ? messages[messages.length - 1] : null;
};

// 删除单条消息
export const deleteMessage = (timestamp) => {
  const messages = getAllMessages();
  const updatedMessages = messages.filter(msg => msg.timestamp !== timestamp);
  localStorage.setItem(CHAT_MESSAGES_KEY, JSON.stringify(updatedMessages));
  return updatedMessages;
};

// 清除所有消息
export const clearAllMessages = () => {
  localStorage.removeItem(CHAT_MESSAGES_KEY);
};

// 更新用户信息
export const updateUserData = (userData) => {
  localStorage.setItem(CHAT_USER_DATA_KEY, JSON.stringify(userData));
};